package com.base.component.app.apple;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.gitee.magic.core.exception.ApplicationException;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class AppleAuth {
	
	public PrivateKey getPrivateKey(InputStream inputStream,String password) {
		try {
			KeyStore.PrivateKeyEntry privateKeyEntry = P12Utils
					.getFirstPrivateKeyEntryFromP12InputStream(inputStream, password);
			Certificate certificate = privateKeyEntry.getCertificate();
			if (!(certificate instanceof X509Certificate)) {
				throw new KeyStoreException(
						"Found a certificate in the provided PKCS#12 file, but it was not an X.509 certificate.");
			}
			return privateKeyEntry.getPrivateKey();
		} catch (final KeyStoreException e) {
			throw new ApplicationException(e);
		} catch (IOException e) {
			throw new ApplicationException(e);
		}
	}
	
	/**
	 * https://developer.apple.com/documentation/appstoreserverapi/generating_json_web_tokens_for_api_requests
	 * @param bundleId
	 * @param kid
	 * @param iss
	 * @param privateKey
	 * @return
	 */
	public String getJwt(String bundleId, String kid, String iss, PrivateKey privateKey) {
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "ES256");//加密算法
        header.put("kid", kid);
        header.put("typ", "JWT");
        Map<String, Object> claims = new HashMap<>();
        claims.put("iss", iss);
        long now = System.currentTimeMillis() / 1000;
        claims.put("iat", now);
        claims.put("exp", now + 86400 * 180);
        claims.put("aud", "https://appleid.apple.com");
        claims.put("bid", bundleId);
        return Jwts.builder().setHeader(header).setClaims(claims).signWith(SignatureAlgorithm.ES256, privateKey).compact();
    }

	public String generateClientSecret(String clientId, String kid, String iss, String key) {
        try {
            Map<String, Object> header = new HashMap<String, Object>();
            header.put("kid", kid);
            Map<String, Object> claims = new HashMap<String, Object>();
            claims.put("iss", iss);
            long now = System.currentTimeMillis() / 1000;
            claims.put("iat", now);
            claims.put("exp", now + 86400 * 180);
            claims.put("aud", "https://appleid.apple.com");
            claims.put("sub", clientId);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            return Jwts.builder().setHeader(header).setClaims(claims).signWith(SignatureAlgorithm.ES256, privateKey).compact();
        } catch (Exception e) {
        	throw new ApplicationException(e);
        }
    }

    public static void main(String[] args) throws Exception {
        String clientId="cn.abuyaw.app";
        String kid="S7FSJDC5Y8";
        String iss="AQD95QP7M9";
        String privateKey = """
	        		MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgFZXA5/jncyITcOTm
	vB1v/9t8KGL0OEabfCCJiBFrR6+gCgYIKoZIzj0DAQehRANCAASvkTVl6KRzQ81I
	LBIqAB+X6BT0xQOyIV2oSsMKiqoFPx4I7+ui638a9rHcnmFfgvoxHMrg0/WtZgOV
	6rBCOZYS
        		""";
        AppleAuth au=new AppleAuth();
        String clientSecret=au.generateClientSecret(clientId, kid, iss, privateKey);
        System.out.println(clientSecret);
        String authorizationCode="c2ce488c176224a14b226a9eaecb79fc6.0.sstx.6zOos3EFf3o3Zf-y5e-cGA";
        String refresh=AppleApi.authToken(clientId,clientSecret,authorizationCode);
        System.out.println(refresh);
//        String re="ra15b63d17d3f471eb17e3ad38d970aeb.0.sstx.DAjQr6sTGnW-x26JpaGddQ";
//        AppleApi.authRevoke(clientId, clientSecret, re);
        
    }
}
